<template>
  <div class="app-container">
    <!-- 搜索表单区域 -->
    <div class="search-section">
      <el-form
        :model="queryParams"
        ref="queryRef"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
        class="search-form"
      >
        <el-form-item label="所属分类" prop="categoryId">
          <el-select
            v-model="queryParams.categoryId"
            placeholder="请选择所属分类"
            clearable
            @change="handleQuery"
            class="custom-select"
          >
            <el-option
              v-for="item in categoryOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入商品名称，如：伊利纯牛奶"
            clearable
            @keyup.enter="handleQuery"
            class="custom-input"
          />
        </el-form-item>
        <el-form-item label="品牌名称" prop="brandName">
          <el-input
            v-model="queryParams.brandName"
            placeholder="请输入品牌名称，如：伊利、金龙鱼"
            clearable
            @keyup.enter="handleQuery"
            class="custom-input"
          />
        </el-form-item>
        <el-form-item label="商品单位" prop="unit">
          <el-input
            v-model="queryParams.unit"
            placeholder="请输入商品单位，如瓶、袋、箱"
            clearable
            @keyup.enter="handleQuery"
            class="custom-input"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery" class="search-btn">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery" class="reset-btn">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-section">
      <el-row :gutter="16" class="action-row">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['transaction:spu:add']"
            class="action-btn add-btn"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['transaction:spu:edit']"
            class="action-btn edit-btn"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['transaction:spu:remove']"
            class="action-btn delete-btn"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['transaction:spu:export']"
            class="action-btn export-btn"
          >导出</el-button>
        </el-col>
        <right-toolbar
          v-model:showSearch="showSearch"
          @queryTable="getList"
        ></right-toolbar>
      </el-row>
    </div>

    <!-- 数据表格区域 -->
    <div class="table-section">
      <el-table
        v-loading="loading"
        :data="spuList"
        @selection-change="handleSelectionChange"
        class="custom-table"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="SPU ID" align="center" prop="id" />
        <el-table-column label="所属分类" align="center" prop="categoryName" />
        <el-table-column label="商品名称" align="center" prop="name" />
        <el-table-column label="品牌名称" align="center" prop="brandName" />
        <el-table-column label="商品单位" align="center" prop="unit" />
        <el-table-column label="商品描述" align="center" prop="description" />
        <el-table-column
          label="商品图片"
          align="center"
          prop="imageUrls"
          width="200"
        >
          <template #default="scope">
            <div class="image-gallery">
              <div v-if="scope.row.imageUrls && scope.row.imageUrls.length > 0" class="image-container">
                <div v-for="(image, index) in getImageArray(scope.row.imageUrls)" :key="index" class="image-item">
                  <el-image
                    :src="image"
                    :preview-src-list="getImageArray(scope.row.imageUrls)"
                    :initial-index="index"
                    style="width: 40px; height: 40px; border-radius: 6px"
                    fit="cover"
                    class="gallery-image"
                  />
                  <div v-if="index === 2 && getImageArray(scope.row.imageUrls).length > 3" class="image-more">
                    +{{ getImageArray(scope.row.imageUrls).length - 3 }}
                  </div>
                </div>
              </div>
              <span v-else class="no-image">暂无图片</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="条形码" align="center" prop="barcode" />
        <el-table-column label="是否上架" align="center" prop="isActive">
          <template #default="scope">
            <el-tag
              :type="scope.row.isActive === '1' ? 'success' : 'info'"
              disable-transitions
              class="status-tag"
            >
              {{ scope.row.isActive === "1" ? "上架" : "下架" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['transaction:spu:edit']"
              class="table-action-btn"
            >修改</el-button>
            <el-button
              link
              type="primary"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['transaction:spu:remove']"
              class="table-action-btn"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-section">
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 添加或修改商品SPU对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body class="custom-dialog">
      <el-form ref="spuRef" :model="form" :rules="rules" label-width="100px" class="dialog-form">
        <el-form-item label="所属分类" prop="categoryId">
          <el-select
            v-model="form.categoryId"
            placeholder="请选择所属分类"
            clearable
            class="dialog-select"
          >
            <el-option
              v-for="item in categoryOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品名称" prop="name">
          <el-input
            v-model="form.name"
            placeholder="请输入商品名称，如：伊利纯牛奶"
            class="dialog-input"
          />
        </el-form-item>
        <el-form-item label="品牌名称" prop="brandName">
          <el-input
            v-model="form.brandName"
            placeholder="请输入品牌名称，如：伊利、金龙鱼"
            class="dialog-input"
          />
        </el-form-item>
        <el-form-item label="商品单位" prop="unit">
          <el-input
            v-model="form.unit"
            placeholder="请输入商品单位，如瓶、袋、箱"
            class="dialog-input"
          />
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            placeholder="请输入内容"
            class="dialog-textarea"
          />
        </el-form-item>
        <el-form-item label="商品图片" prop="imageUrls">
          <div class="image-upload-section">
            <image-upload v-model="form.imageUrls" :limit="5" class="multi-image-upload"/>
            <div class="upload-tips">
              <p>支持上传多张图片，最多5张</p>
              <p>建议尺寸：800x800px，格式：JPG、PNG</p>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="条形码" prop="barcode">
          <el-input v-model="form.barcode" placeholder="请输入条形码" class="dialog-input" />
        </el-form-item>
        <el-form-item label="是否上架" prop="isActive">
          <el-select v-model="form.isActive" placeholder="请选择是否上架" class="dialog-select">
            <el-option label="上架" value="1" />
            <el-option label="下架" value="0" />
          </el-select>
        </el-form-item>
        <!-- 新增规格选择区域 -->
        <el-form-item label="商品规格" prop="selectedSpecs">
          <div class="spec-selection-section">
            <el-checkbox-group v-model="form.selectedSpecs" class="spec-checkbox-group">
              <el-checkbox 
                v-for="spec in specOptions" 
                :key="spec.id" 
                :label="spec.id"
                class="spec-checkbox"
              >
                {{ spec.name }}
              </el-checkbox>
            </el-checkbox-group>
            <div class="spec-tips">
              <p>选择该商品包含的规格，如颜色、尺码、容量等</p>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm" class="submit-btn">确 定</el-button>
          <el-button @click="cancel" class="cancel-btn">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Spu">
import {
  listSpuVo,
  getSpu,
  delSpu,
  addSpu,
  updateSpu,
  addSpuSpec
} from "@/api/transaction/spu";
import { listCategory } from "@/api/transaction/category";
import { listSpec, getSpec } from "@/api/transaction/spec";
import request from '@/utils/request';

// 重新定义addSpuSpec接口，根据后端接口使用URL参数
const addSpuSpecLocal = (spuId, specId) => {
  return request({
    url: `transaction/spu/addSpuSpec?spuId=${spuId}&specId=${specId}`,
    method: 'post'
  });
};

// 获取SPU已关联的规格ID列表
const getSpuSpecsLocal = (spuId) => {
  return request({
    url: `transaction/spu/specs/${spuId}`,
    method: 'get'
  });
};

const { proxy } = getCurrentInstance();

const spuList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
// 分类数据
const categoryOptions = ref([]);
// 规格数据
const specOptions = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    categoryId: null,
    name: null,
    brandName: null,
    unit: null,
    description: null,
    isActive: null,
  },
  rules: {},
});

const { queryParams, form, rules } = toRefs(data);

/** 查询商品SPU列表 */
function getList() {
  loading.value = true;
  console.log('查询参数:', queryParams.value);
  listSpuVo(queryParams.value).then((response) => {
    console.log('API返回数据:', response);
    spuList.value = response.rows;
    total.value = response.total;
    loading.value = false;
    console.log('处理后的数据:', spuList.value);
  });
}

// 处理图片数组
function getImageArray(imageUrls) {
  if (!imageUrls) return [];
  if (Array.isArray(imageUrls)) return imageUrls;
  if (typeof imageUrls === 'string') {
    // 如果是逗号分隔的字符串，转换为数组
    const urls = imageUrls.split(',').filter(url => url.trim());
    console.log('图片URL处理:', imageUrls, '->', urls);
    return urls;
  }
  return [];
}

/** 获取分类列表 */
async function getCategoryList() {
  try {
    const response = await listCategory({ level: 2 }); // 固定查询二级分类
    console.log('分类数据:', response);
    categoryOptions.value = response.rows || response.data || [];
    console.log('处理后的分类选项:', categoryOptions.value);
  } catch (err) {
    console.error('获取分类失败:', err);
    proxy.$modal.msgError('获取分类失败');
  }
}

/** 获取规格列表 */
async function getSpecList() {
  try {
    const response = await listSpec();
    console.log('规格数据:', response);
    specOptions.value = response.rows || response.data || [];
    console.log('处理后的规格选项:', specOptions.value);
  } catch (err) {
    console.error('获取规格失败:', err);
    proxy.$modal.msgError('获取规格失败');
  }
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    categoryId: null,
    name: null,
    brandName: null,
    unit: null,
    description: null,
    imageUrls: [],
    barcode: null,
    isActive: null,
    selectedSpecs: [], // 新增：选中的规格ID数组
    delFlag: null,
    createTime: null,
    updateTime: null,
  };
  proxy.resetForm("spuRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加商品SPU";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  console.log("点击了修改", row);
  reset();
  const _id = row.id || ids.value;
  getSpu(_id).then((response) => {
    form.value = response.data;
    // 确保imageUrls是数组格式
    if (form.value.imageUrls && typeof form.value.imageUrls === 'string') {
      form.value.imageUrls = form.value.imageUrls.split(',').filter(url => url.trim());
    }
    
    // 获取该SPU已关联的规格
    getSpuSpecsLocal(form.value.id).then((specResponse) => {
      console.log('SPU已关联的规格:', specResponse);
      if (specResponse.data && Array.isArray(specResponse.data)) {
        // 将规格ID数组转换为数字数组
        form.value.selectedSpecs = specResponse.data.map(id => Number(id));
        console.log('设置已选规格:', form.value.selectedSpecs);
      } else {
        form.value.selectedSpecs = [];
      }
    }).catch((error) => {
      console.error('获取SPU规格失败:', error);
      form.value.selectedSpecs = [];
    });
    
    open.value = true;
    title.value = "修改商品SPU";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["spuRef"].validate((valid) => {
    if (valid) {
      // 确保提交时imageUrls是字符串格式
      const submitData = { ...form.value };
      if (Array.isArray(submitData.imageUrls)) {
        submitData.imageUrls = submitData.imageUrls.join(',');
      }
      
      // 移除规格选择数据，因为规格关联需要单独处理
      const selectedSpecs = submitData.selectedSpecs;
      delete submitData.selectedSpecs;
      
      if (form.value.id != null) {
        // 修改操作
        updateSpu(submitData).then((response) => {
          // 处理规格关联 - 确保spuId是数字
          const spuId = Number(form.value.id);
          console.log('修改操作 - SPU ID:', spuId);
          // 修改时需要先删除旧的规格关联，再创建新的
          handleSpecAssociationForUpdate(spuId, selectedSpecs);
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        // 新增操作
        addSpu(submitData).then((response) => {
          console.log('新增SPU完整响应:', response);
          
          // 后端现在返回完整的SPU对象，直接获取ID
          let newSpuId = null;
          
          if (response.data && response.data.id) {
            newSpuId = Number(response.data.id);
            console.log('从response.data.id获取SPU ID:', newSpuId);
          }
          
          console.log('最终获取到的SPU ID:', newSpuId);
          
          if (!newSpuId || isNaN(newSpuId)) {
            console.error('无法获取有效的SPU ID，响应结构:', response);
            proxy.$modal.msgError('新增SPU成功，但无法获取有效的SPU ID，规格关联失败');
            open.value = false;
            getList();
            return;
          }
          
          // 处理规格关联
          handleSpecAssociation(newSpuId, selectedSpecs);
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 处理规格关联 */
async function handleSpecAssociation(spuId, selectedSpecs) {
  if (!selectedSpecs || selectedSpecs.length === 0) {
    console.log('没有选择规格，跳过规格关联');
    return;
  }
  
  // 验证spuId是否有效
  if (!spuId || spuId === 'undefined' || spuId === undefined || isNaN(spuId)) {
    console.error('spuId无效:', spuId);
    proxy.$modal.msgError('SPU ID无效，无法创建规格关联');
    return;
  }
  
  // 确保spuId是数字
  const numericSpuId = Number(spuId);
  if (isNaN(numericSpuId)) {
    console.error('spuId转换为数字失败:', spuId);
    proxy.$modal.msgError('SPU ID格式错误，无法创建规格关联');
    return;
  }
  
  try {
    // 为每个选中的规格创建关联
    for (const specId of selectedSpecs) {
      // 验证specId是否有效
      if (!specId || specId === 'undefined' || specId === undefined || isNaN(specId)) {
        console.error('specId无效:', specId);
        continue;
      }
      
      // 确保specId是数字
      const numericSpecId = Number(specId);
      if (isNaN(numericSpecId)) {
        console.error('specId转换为数字失败:', specId);
        continue;
      }
      
      console.log('创建规格关联:', { spuId: numericSpuId, specId: numericSpecId });
      // 根据后端接口定义，使用URL参数传递spuId和specId
      await addSpuSpecLocal(numericSpuId, numericSpecId);
    }
    console.log('规格关联处理完成');
  } catch (error) {
    console.error('规格关联失败:', error);
    proxy.$modal.msgError('规格关联失败');
  }
}

/** 处理规格关联 (修改时) */
async function handleSpecAssociationForUpdate(spuId, selectedSpecs) {
  if (!selectedSpecs || selectedSpecs.length === 0) {
    console.log('没有选择规格，跳过规格关联');
    return;
  }

  // 验证spuId是否有效
  if (!spuId || spuId === 'undefined' || spuId === undefined || isNaN(spuId)) {
    console.error('spuId无效:', spuId);
    proxy.$modal.msgError('SPU ID无效，无法创建规格关联');
    return;
  }

  // 确保spuId是数字
  const numericSpuId = Number(spuId);
  if (isNaN(numericSpuId)) {
    console.error('spuId转换为数字失败:', spuId);
    proxy.$modal.msgError('SPU ID格式错误，无法创建规格关联');
    return;
  }

  try {
    // 先删除旧的规格关联
    await request({
      url: `transaction/spu/specs/delete?spuId=${numericSpuId}`,
      method: 'delete'
    });
    console.log('旧规格关联删除成功');

    // 为每个选中的规格创建关联
    for (const specId of selectedSpecs) {
      // 验证specId是否有效
      if (!specId || specId === 'undefined' || specId === undefined || isNaN(specId)) {
        console.error('specId无效:', specId);
        continue;
      }
      
      // 确保specId是数字
      const numericSpecId = Number(specId);
      if (isNaN(numericSpecId)) {
        console.error('specId转换为数字失败:', specId);
        continue;
      }
      
      console.log('创建规格关联:', { spuId: numericSpuId, specId: numericSpecId });
      // 根据后端接口定义，使用URL参数传递spuId和specId
      await addSpuSpecLocal(numericSpuId, numericSpecId);
    }
    console.log('规格关联处理完成');
  } catch (error) {
    console.error('规格关联失败:', error);
    proxy.$modal.msgError('规格关联失败');
  }
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除商品SPU编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delSpu(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "transaction/spu/export",
    {
      ...queryParams.value,
    },
    `spu_${new Date().getTime()}.xlsx`
  );
}

// 页面初始化
getList();
getCategoryList();
getSpecList();
</script>

<style scoped>
.spec-selection-section {
  width: 100%;
}

.spec-checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 8px;
}

.spec-checkbox {
  margin-right: 0;
}

.spec-tips {
  color: #909399;
  font-size: 12px;
  line-height: 1.4;
}

.spec-tips p {
  margin: 0;
}
</style>
